package com.hmilyylimh.cloud.async.work;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;

public class Work01 {
    public static void main(String[] args) throws Exception{
        CompletableFuture<Integer> TASK_A1 = CompletableFuture.supplyAsync(() -> 1);

        CompletableFuture<Integer> TASK_B1 = TASK_A1.thenApplyAsync(t -> 2);

        CompletableFuture<Integer> TASK_C1 = TASK_A1.thenApplyAsync(t -> 3);


        CompletableFuture<Integer> result1 =
                TASK_B1.thenCombine(TASK_C1, Integer::sum)
                        .thenCombine(TASK_A1, Integer::sum)
                        .thenApplyAsync(i -> i + 4);



        CompletableFuture<Integer> TASK_A2 = CompletableFuture.supplyAsync(() -> 1);

        CompletableFuture<Integer> TASK_B2 = TASK_A2.thenApplyAsync(t -> 2);

        CompletableFuture<Integer> TASK_C2 = TASK_A2.thenApplyAsync(t -> 3);

        CompletableFuture<Integer> result2 = TASK_B2.applyToEither(TASK_C2, Function.identity())
                .thenCombine(TASK_A2, Integer::sum)
                .thenApplyAsync(i -> i + 4);

        CompletableFuture<Integer> r = result1.thenCombine(result2, Integer::sum);

        try {
            Integer n = r.get(5, TimeUnit.SECONDS);
            System.out.println(n);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }


    }
}
